package com.clt.web.controller;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.clt.web.common.Pay;
import com.clt.web.common.WeChat;
import com.clt.web.common.WeiXinPropertiesUtil;
import com.clt.web.pojo.WxPackages;
import com.clt.web.utils.MapUtil;
import com.clt.web.utils.SHA1Util;

/**
 * 微信支付
 * 
 * @author Zhou Yingying
 * @createDate 2015/12/15
 */
@Controller
@RequestMapping("/weixin/pay")
public class WeixinPayController {

	private final Logger log = LoggerFactory.getLogger(getClass());

	/**
	 * 得到页面调用微信支付接口 需要的参数 参数列表： timestamp, nonceStr, signature, package,
	 * signType, paySign
	 * 
	 * @return ModelAndView对象
	 * @throws Exception
	 */
	@RequestMapping("/payButton")
	public ModelAndView Pay(WxPackages wxPackage, HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView("mobile/wxConfirm");
		// 先把页面需要的所有参数置空
		String jsapiTicket = null;
		String url = null;
		String timeStamp = null;
		String nonceStr = null;
		String signature = null;
		// 得到接口，如果失败的话获取相应的错误信息
		try {
			jsapiTicket = WeChat.getTicket();
			mav.addObject("errorMSG", "");
		} catch (KeyManagementException e) {
			log.error("打开支付接口获取ticket错误:{}", e);
			mav.addObject("errorMSG", e.getMessage());
		} catch (NoSuchAlgorithmException e) {
			log.error("打开支付接口获取ticket错误:{}", e);
			mav.addObject("errorMSG", e.getMessage());
		} catch (NoSuchProviderException e) {
			log.error("打开支付接口获取ticket错误:{}", e);
			mav.addObject("errorMSG", e.getMessage());
		} catch (InterruptedException e) {
			log.error("打开支付接口获取ticket错误:{}", e);
			mav.addObject("errorMSG", e.getMessage());
		} catch (ExecutionException e) {
			log.error("打开支付接口获取ticket错误:{}", e);
			mav.addObject("errorMSG", e.getMessage());
		} catch (IOException e) {
			log.error("打开支付接口获取ticket错误:{}", e);
			mav.addObject("errorMSG", e.getMessage());
		}
		url = request.getRequestURL().toString(); // 获取调用js接口页面的url
		log.info("获取本页面url为:{},ticket为:{}", url, jsapiTicket);
		Map<String, String> map = WeChat.jsApiSign(jsapiTicket, url);
		timeStamp = map.get("timestamp");
		nonceStr = map.get("nonceStr");
		signature = map.get("signature");
		// 设置wxPackage的必要参数
		// 其余需要页面传过来的参数因为传入整个对象wxPackage的缘故，已经存在于此对象中
		// 注：选填的参数没有填写
		//获取url
		String basePath = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort()+ request.getContextPath();
		wxPackage.setNotify_url(basePath+"/weixin/pay/returnPay"); // 支付完成后返回的页面
		wxPackage.setSpbill_create_ip(Pay.getIp(request));// 获取用户端IP
		//wxPackage.setOut_trade_no("12345rtyuio432156asdfghkiueyw");//订单号
		//wxPackage.setTotal_fee(1);//金额
		//wxPackage.setBody("哈a1");//商品描述
		wxPackage.setTrade_type("JSAPI");//支付类型 公众号支付
		wxPackage.setProductId("123456");//支付类型是JSAPI时 必填
		
		
		String openId = null==request.getSession().getAttribute("myOpenid")?null
				:request.getSession().getAttribute("myOpenid").toString();
		log.info("微信支付   获取当前操作人的openId={}",openId);
		
		String prepay_id = Pay.unifiedorder(request, wxPackage.getTotal_fee()+"", 
				wxPackage.getBody(), openId, 
				wxPackage.getOut_trade_no(), nonceStr, wxPackage.getNotify_url(),
				wxPackage.getTrade_type(), wxPackage.getProductId());
		String packageValue = "prepay_id=" + prepay_id;
		mav.addObject("package", packageValue); // 将得到的package参数写入mav对象传给页面
		// paySign获取
		Map<String, String> paySign = new HashMap<String, String>();
		paySign.put("appid", WeiXinPropertiesUtil.getAppId());
		paySign.put("timestamp", timeStamp); // 所有参数名都必须是小写
		paySign.put("noncestr", nonceStr);
		paySign.put("weixinPackage", packageValue);
		paySign.put("appkey", WeiXinPropertiesUtil.getPartnerKey()); // 注：此处的appkey需要根据实际情况填写
		String String3 = MapUtil.createSign(paySign, false);
		String PaySign = SHA1Util.encode(String3);
		
		mav.addObject("paySign", PaySign);
		mav.addObject("appId", WeiXinPropertiesUtil.getAppId()); // 得到输入流中的AppId以供页面使用
		mav.addObject("timeStamp", timeStamp);
		mav.addObject("nonceStr", nonceStr);
		mav.addObject("signature", signature);
		mav.addObject("signType", "MD5"); // 签名方式默认为SHA1,新版本用MD5
		return mav;
	}
	
	/**
	 * 支付结果
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping("/returnPay")
	public ModelAndView save(HttpServletRequest req, HttpServletResponse resp) {
		ModelAndView mav = new ModelAndView("mobile/returnPay");
		return mav;
	}
	
	@RequestMapping("/start")
	public String start(){
		return "mobile/wxPay";
	}
	
}
